import DBConnection from "../../service/unit/mysql/DBConnection";
interface IData {
    anthology:string
    author:string
}
export default async function createAnthology(CONN:DBConnection, data:IData){
    const {anthology} = data;
    const TABLE_NAME= 'anthology';
    const QUERY_RESULT = await queryAnthology(CONN, TABLE_NAME, {anthology});
    const IS_ANTHOLOGY_EXIST = QUERY_RESULT.length>0;

    if(IS_ANTHOLOGY_EXIST){
        await updateAnthology(CONN, TABLE_NAME, {anthology});
    }else{
        await insertAnthology(CONN, TABLE_NAME, data);
    }
}

function queryAnthology(CONN, TABLE_NAME, CONDITION){
    const _KNEX = CONN.knex;
    const {anthology} = CONDITION;
    const _anthology = CONN.strEncode(anthology);
    return _KNEX.where({anthology:_anthology}).select().table(TABLE_NAME);
}

//将指定anthology的is_active置为1
function updateAnthology(CONN:DBConnection, TABLE_NAME, CONDITION) {
    const _KNEX = CONN.knex;
    const {anthology} = CONDITION;
    const _anthology = CONN.strEncode(anthology);
    return _KNEX.where({anthology:_anthology}).update({is_active:1}).table(TABLE_NAME);
}

//插入新的anthology
function insertAnthology(conn:DBConnection, TABLE_NAME, DATA:IData) {
    const {anthology, author} = DATA;
    return conn.Insert.insert(TABLE_NAME,{anthology, author})
}